package club.framework.web.application.sys.user.service.impl;


import club.framework.web.application.sys.user.entity.User;
import club.framework.web.application.sys.user.mapper.UserMapper;
import club.framework.web.application.sys.user.service.IUserService;
import club.framework.web.base.common.Constants;
import club.framework.web.base.common.Crypto;
import club.framework.web.base.entity.BasePageReqEntity;
import club.framework.web.base.entity.BasePageResultEntity;
import club.framework.web.base.exception.CryptoException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Stream;

@Service
public class UserServiceImpl implements IUserService {


    private static final Logger log = LogManager.getLogger(UserServiceImpl.class);

    private static final String USER_MENU_DELIMITER = ",";

    private static final String ROOT_MENU = "j1_1";

    @Resource
    private UserMapper userMapper;

    @Override
    public User getObject(User user) {
        return null;
    }

    @Override
    public User getObject(int id) {
        return userMapper.getUserById(id);
    }

    @Override
    public User getObject(long uid) {
        return null;
    }

    @Override
    public int save(User user) {
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        try {
            user.setPassword(Crypto.getInstance().encrypt(user.getPassword(), Constants.DB_USERINFO_ENCRYPT_KEY));
        } catch (Exception e) {
            log.error("保存用户,密码: {},加密错误: {}", user.getPassword(), e.getMessage());
            throw new CryptoException(e.getMessage());
        }
        return userMapper.save(user);
    }

    @Override
    public int delete(User user) {
        return 0;
    }

    @Override
    public int delete(int id) {
        return userMapper.delete(id);
    }

    @Override
    public int delete(long uid) {
        return 0;
    }

    @Override
    public int update(User user) {
        user.setUpdateTime(new Date());
        try {
            user.setPassword(Crypto.getInstance().encrypt(user.getPassword(), Constants.DB_USERINFO_ENCRYPT_KEY));
        } catch (Exception e) {
            log.error("修改用户,密码: {},加密错误: {}", user.getPassword(), e.getMessage());
            throw new CryptoException(e.getMessage());
        }
        return userMapper.update(user);
    }

    @Override
    public BasePageResultEntity<User> queryPage(BasePageReqEntity<User> basePageReqEntity) {
        int totalCount = userMapper.queryTotalCount(basePageReqEntity.getObj());
        List<User> queryPageList = userMapper.queryPage(basePageReqEntity);
        BasePageResultEntity<User> basePageResultEntity = new BasePageResultEntity<>();
        basePageResultEntity.setRows(queryPageList);
        basePageResultEntity.setTotal(totalCount);
        return basePageResultEntity;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveUserMenu(int userId, String menuIds) {
        userMapper.deleteUserMenuByUserId(userId);
        List<Map<String, Object>> userMenuList = new ArrayList<>();
        Stream.of(menuIds.split(USER_MENU_DELIMITER)).forEach(e -> {
            Map<String, Object> userMenuMap = new HashMap<String, Object>();
            if (!ROOT_MENU.equals(e)) {
                userMenuMap.put("userId", userId);
                userMenuMap.put("menuId", e);
                userMenuList.add(userMenuMap);
            }
        });
        return userMapper.batchSaveUserMenu(userMenuList);
    }
}
